package com.luli.entity;

/**
 * 陆离
 * 2024/12/10
 */

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DepartmentHierarchyQuery {
    // 通过当前部门ID递归查找下级部门，构建并返回包含当前部门及其下级部门的部门树结构
    public static Department getSubDepartmentsTree(int currentDepartmentId) {
        // 获取所有部门信息并存储到Map中，方便后续快速查找关联
        List<Department> allDepartments = DatabaseUtil.getAllDepartments();
        Map<Integer, Department> departmentMap = new HashMap<>();
        for (Department department : allDepartments) {
            departmentMap.put(department.getDepartmentId(), department);
        }

        // 构建部门树，通过递归关联下级部门
        Department rootDepartment = departmentMap.get(currentDepartmentId);
        buildSubDepartmentTree(rootDepartment, departmentMap);

        return rootDepartment;
    }

    private static void buildSubDepartmentTree(Department department, Map<Integer, Department> departmentMap) {
        if (department == null) {
            return;
        }
        List<Department> subDepartments = department.getSubDepartments();
        for (Department allDepartment : departmentMap.values()) {
            if (allDepartment.getParentDepartmentId() == department.getDepartmentId()) {
                subDepartments.add(allDepartment);
                buildSubDepartmentTree(allDepartment, departmentMap);
            }
        }
    }

    // 用于打印部门树结构，直观展示当前部门及其下级部门信息
    public static void printDepartmentTree(Department department, int level) {
        if (department == null) {
            return;
        }
        StringBuilder prefix = new StringBuilder();
        for (int i = 0; i < level; i++) {
            prefix.append("  ");
        }
        System.out.println(prefix + department.getDepartmentName());
        List<Department> subDepartments = department.getSubDepartments();
        for (Department subDepartment : subDepartments) {
            printDepartmentTree(subDepartment, level + 1);
        }
    }


    public static void main(String[] args) {
        int currentDepartmentId = 3;  // 这里假设部门ID为1的部门作为起始部门，可根据实际需求替换
        Department departmentTree = DepartmentHierarchyQuery.getSubDepartmentsTree(currentDepartmentId);
        DepartmentHierarchyQuery.printDepartmentTree(departmentTree, 0);
    }
}
